Date Functions

  • Code

    JavaScript Date Object

    Using the new Date() Constructor
    
    const date = new Date();
    console.log(date);
    
    //OUTPUT
    Sun Sep 10 2023 23:12:45 GMT+0530 (India Standard Time)
    
    Passing Individual Date Components
    
    
    /**
     Let's understand the arguments passed.
     Starting from the left to right,
       - 2023 represents the Year
       - 8 represents the Month. It is an idex value starts 
         with 0 which repreents January month in the English
         calendar, 1 for February, and so on.
       - 10 represents the day between 1 to 31.
       - 23 represents the hour between 1 to 24.
       - 15 represents the minute.
       - 34 represents the second.
       - 0 represent the millisecond.
    
    */
    const date = new Date(2023, 8, 10, 23, 15, 34, 0);
    console.log(date);
    
    
    //OUTPUT
    Sun Sep 10 2023 23:15:34 GMT+0530 (India Standard Time)
    
    
    Parsing string to a JavaScript Date
    
    
    const date = new Date("2013-09-10T13:24:00");
    console.log(date);
    
    
    //OUTPUT
    
    Tue Sep 10 2013 13:24:00 GMT+0530 (India Standard Time)
    
    Using Timestamps
    
    const date = new Date(1688737100000);
    console.log(date);
    
    
    //OUTPUT
    Fri Jul 07 2023 19:08:20 GMT+0530 (India Standard Time)
    

    get the current date

    Current date using JavaScript Date Methods
    
    
    const date = new Date();
    
    date.getFullYear(); // 2023
    date.getMonth(); // 8
    date.getDate(); // 11
    
    
    
    
    const date = new Date();
    
    const day = date.getDate();
    const month = date.getMonth() + 1; // The month index starts from 0
    const year = date.getFullYear();
    
    let currentDate = `${day}/${month}/${year}`;
    console.log(currentDate); // 10/9/2023
    
    
    OR
    
    let currentDate = `${year}-${month}-${day}`;
    
    
    OR
    
    const month = String(date.getMonth()+1).padStart(2,"0"); // Output "09"
    
    
    Current date using the now() method
    
    new Date(Date.now()); // Mon Sep 11 2023 08:01:44 GMT+0530 (India Standard Time)
    
    new String(new Date(Date.now())).slice(4, 15); // "Sep 11 2023"
    
    
    Current Date using the toJSON() method
    
    new Date().toJSON(); // "2023-09-11T02:41:56.619Z"
    
    new Date().toJSON().slice(0, 10); // "2023-09-11"
    
    Current Date using the toLocaleDateString() method
    
    const date = new Date().toLocaleDateString();
    console.log(date); // "11/09/2023"
    
    
    
    const date = new Date().toLocaleDateString("de-DE");
    console.log(date); // 17.6.2022
    

    How to calculate elapsed time

    
    
    // Define two Date objects representing the start and end dates
    const startDate = new Date('2023-08-15T00:00:00');
    const endDate = Date.now(); // Current date and time in milliseconds
    
    // Calculate the time difference in milliseconds
    const timeDifferenceMS = endDate - startDate;
    
    // Calculate the elapsed time in seconds, minutes, hours, and days
    const timeDifferenceSecs = Math.floor(timeDifferenceMS / 1000);
    const timeDifferenceMins = Math.floor(timeDifferenceMS / 60000);
    const timeDifferenceHours = Math.floor(timeDifferenceMS / 3600000);
    const timeDifferenceDays = Math.floor(timeDifferenceMS / 86400000);
    
    console.log(`Time difference in milliseconds: ${timeDifferenceMS}`);
    console.log(`Time difference in seconds: ${timeDifferenceSecs}`);
    console.log(`Time difference in minutes: ${timeDifferenceMins}`);
    console.log(`Time difference in hours: ${timeDifferenceHours}`);
    console.log(`Time difference in days: ${timeDifferenceDays}`);
    
    

    Date diff

    
    
    let date1 = new Date("01/16/2024");
    let date2 = new Date("01/26/2024");
    
    // Convert dates to UTC timestamps
    let utc1 = Date.UTC(date1.getFullYear(), date1.getMonth(), date1.getDate());
    let utc2 = Date.UTC(date2.getFullYear(), date2.getMonth(), date2.getDate());
    
    // Calculate the time difference in milliseconds
    let timeDiff = Math.abs(utc2 - utc1);
    
    // Convert milliseconds to days
    let daysDiff = Math.ceil(timeDiff / (1000 * 60 * 60 * 24));
    
    // Display the result
    console.log(`Total number of days between dates:
    ${date1.toDateString()} and ${date2.toDateString()} is: ${daysDiff} days`);
    
    
    //OUTPUT
    
    Total number of days between dates:
    Tue Jan 16 2024 and Fri Jan 26 2024 is: 10 days
    
    

    Add Days to Current Date

    
    // Get current date
    var date = new Date();
    
    // Add five days to current date
    date.setDate(date.getDate() + 5);
    
    console.log(date);
    
    
    
    // Specific date
    var date = new Date('August 21, 2021 16:45:30');
    
    // Add ten days to specified date
    date.setDate(date.getDate() + 10);
    
    console.log(date);
    
    
    
    

    Compare Dates

    
    // Create two Date objects
    const firstDate = new Date('2024-02-06T12:00:00');
    const secondDate = new Date('2024-02-07T12:00:00');
    
    // Convert the dates to ISO strings
    const firstISODate = firstDate.toISOString();
    const secondISODate = secondDate.toISOString();
    
    
    // Compare the two ISO strings
    if (firstISODate === secondISODate) {
      console.log("The dates are equal.");
    } else if (firstISODate < secondISODate) {
      console.log("firstDate is before secondDate.");
    } else {
      console.log("firstDate is after secondDate.");
    }
    
    

    JavaScript Date Formatting

    
    
    const date = new Date(Date.UTC(2013, 09, 17, 13, 10, 20));
    
    console.log("In en-US: ", new Intl.DateTimeFormat("en-US").format(date));  // In en-US:  10/17/2013
    
    console.log("In en-GB: ", new Intl.DateTimeFormat("en-GB").format(date)); // In en-GB:  17/10/2013
    
    console.log("In ko-KR: ", new Intl.DateTimeFormat("ko-KR").format(date)); // In ko-KR:  2013. 10. 17.
    
    

    Example 1

    
    function  date_last_performed1(){
    		 d1=$('.date_last_performed2').val();
    		 d2=$('.date_last_performed1').val();
    
    		 dd1='';
    		 if(d1!='' && d2!=''){
    			
    			fd=new Date(d1);			
    			fd.setMonth(fd.getMonth()+parseInt(d2));
    
    			td=fd.getDate();
    			tm=fd.getMonth()+1;
    			ty=fd.getFullYear();
    
    			dd1=tm+"-"+td+"-"+ty;			
    
    		 }		 
    				
    		$('.date_last_performed3').val(dd1);
    	}
    

    Example 2

    
    
    function calculateDates(){
          let installed_date=$('#installed_date').val();
          var warranty_days=$('.warranty_id option:selected').attr("data-days");     
          var maintenance_days=$('.maintenance_id option:selected').attr("data-days"); 
    
          if(installed_date!=''){
    
                installed_date=installed_date.split("-");
                if(warranty_days>0){
                      
                      wanrrantyEndDate=new Date(installed_date[2]+"-"+installed_date[1]+"-"+installed_date[0]);                 
                      wanrrantyEndDate.setDate(wanrrantyEndDate.getDate()+parseInt(warranty_days)-1);
                     
    
                      wanrrantyEndDate=wanrrantyEndDate.getDate()+"-"+(wanrrantyEndDate.getMonth()+1)+"-"+wanrrantyEndDate.getFullYear();                  
                      $('.warranty_end_date').val(wanrrantyEndDate);
                }
    
                if(maintenance_days>0){
                      maintenanceEndDate=new Date(installed_date[2]+"-"+installed_date[1]+"-"+installed_date[0]);
                      maintenanceEndDate.setDate(maintenanceEndDate.getDate()+parseInt(maintenance_days)-1);
    
                      maintenanceEndDate=maintenanceEndDate.getDate()+"-"+(maintenanceEndDate.getMonth()+1)+"-"+maintenanceEndDate.getFullYear();
                      $('.next_pm_date').val(maintenanceEndDate);
                }
    
          }       
    
    
    }